from flask import Blueprint
from flask_json import as_json
from flask_jwt_extended import get_jwt_identity, jwt_required
from app.models import LoginLog, CommonResult

loginLog = Blueprint('auth_user_log', __name__, url_prefix='/logs')


# 注册蓝图
def register_controller(app):
    app.register_blueprint(loginLog)


# 获取登录日志列表
@loginLog.get('/list')
@jwt_required()
@as_json
def login_logs():
    user_id = get_jwt_identity()
    login_log_list = LoginLog.query.filter_by(user_id=user_id).all()
    return CommonResult(data=login_log_list)


# 获取前N条记录
@loginLog.get('/top/<int:top_num>')
@jwt_required()
@as_json
def login_log_top(top_num):
    if top_num > 100:
        return CommonResult(code=500, msg='最多显示前100条')
    user_id = get_jwt_identity()
    login_log_list = LoginLog.query.filter_by(user_id=user_id).order_by(
        LoginLog.id.desc()).limit(top_num).all()
    return CommonResult(data=login_log_list)
